import 'package:flutter/material.dart';
import 'package:mall/utils/alert/alert_util.dart';
import 'package:mall/utils/client/file_service.dart';
import 'package:photo_view/photo_view_gallery.dart';

class ImagePreviewDialog extends StatefulWidget {
  const ImagePreviewDialog({super.key, required this.imgList, this.index = 0});

  final List imgList;
  final int index;

  @override
  State<ImagePreviewDialog> createState() => _ImagePreviewDialogState();
}

class _ImagePreviewDialogState extends State<ImagePreviewDialog> {
  int _currentIndex = 0;
  PageController? _controller;

  void _onLongPress(BuildContext context) {
    AlertUtil.showAlert(
      context,
      content: '是否保存图片?',
      onConfirm: () {
        FileService.toDoSave(widget.imgList[_currentIndex], context);
      },
    );
  }

  @override
  void initState() {
    super.initState();
    _controller = PageController(initialPage: widget.index);
    setState(() {
      _currentIndex = widget.index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: GestureDetector(
        onTap: () => Navigator.of(context).pop(),
        onLongPress: () => _onLongPress(context),
        child: Container(
          color: Colors.black,
          child: PhotoViewGallery.builder(
            scrollPhysics: const BouncingScrollPhysics(),
            builder: (context, index) {
              return PhotoViewGalleryPageOptions(
                imageProvider: NetworkImage(widget.imgList[index]),
              );
            },
            itemCount: widget.imgList.length,
            backgroundDecoration: null,
            enableRotation: true,
            pageController: _controller,
            onPageChanged: (index) {
              setState(() {
                _currentIndex = index;
              });
            },
          ),
        ),
      ),
    );
  }
}
